package com.jui.material.views;

import com.jui.material.R;
import com.jui.material.utils.Utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RadioButton extends CustomView {

  int backgroundColor = getResources().getColor(R.color.md_checkedColor);
  Check checkView;

  boolean press = false;
  boolean check = false;

  OnCheckListener onCheckListener;

  private Paint thumbPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
  private int mThumbRadius;
  private int mThumbColor;
  private long mStartTime;

  private int mState = 1;//1-->normal,2-->down,3-->up

  public RadioButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAttributes(attrs);
  }

  // Set atributtes of XML to View
  protected void setAttributes(AttributeSet attrs) {

    setBackgroundResource(R.drawable.background_checkbox);

    // Set size of view
    setMinimumHeight(Utils.dpToPx(48, getResources()));
    setMinimumWidth(Utils.dpToPx(48, getResources()));

    // Set background Color
    // Color by resource
    int bacgroundColor = attrs.getAttributeResourceValue(ANDROIDXML, "background", -1);
    if (bacgroundColor != -1) {
      setBackgroundColor(getResources().getColor(bacgroundColor));
    } else {
      // Color by hexadecimal
      // Color by hexadecimal
      int background = attrs.getAttributeIntValue(ANDROIDXML, "background", -1);
      if (background != -1) setBackgroundColor(background);
    }

    final boolean checked = attrs.getAttributeBooleanValue(MATERIALDESIGNXML, "md_checked", false);
    check = checked;
    
    mThumbRadius = getResources().getDimensionPixelSize(R.dimen.md_radio_thumb_radius);
    mThumbColor = getResources().getColor(R.color.md_checkedColor);
    thumbPaint.setColor(mThumbColor);

    checkView = new Check(getContext());
    checkView.setId(View.generateViewId());
    RelativeLayout.LayoutParams params =
        new LayoutParams(Utils.dpToPx(20, getResources()), Utils.dpToPx(20, getResources()));
    params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    checkView.setLayoutParams(params);
    addView(checkView);

    // Adding text view to checkbox
    int textResource = attrs.getAttributeResourceValue(ANDROIDXML, "text", -1);
    String text = null;

    if (textResource != -1) {
      text = getResources().getString(textResource);
    } else {
      text = attrs.getAttributeValue(ANDROIDXML, "text");
    }

    if (text != null) {
      params.removeRule(RelativeLayout.CENTER_IN_PARENT);
      params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
      TextView textView = new TextView(getContext());
      RelativeLayout.LayoutParams textViewLayoutParams =
          new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      textViewLayoutParams.addRule(RelativeLayout.RIGHT_OF, checkView.getId());
      textViewLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
      textViewLayoutParams.setMargins(10, 0, 0, 0);
      textView.setLayoutParams(textViewLayoutParams);
      textView.setText(text);

      addView(textView);
    }
    
        setChecked(checked);
    
  }

  @Override
  public void invalidate() {
    checkView.invalidate();
    super.invalidate();
  }


  @Override
  public boolean onTouchEvent(MotionEvent event) {
    
    if (isEnabled()) {
      isLastTouch = true;
      switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
          changeBackgroundColor((check) ? makePressColor() : getResources().getColor(R.color.md_ripple_color));
          mState = 2;
          mStartTime = System.currentTimeMillis();
          invalidate();
          break;

        case MotionEvent.ACTION_MOVE:
          if ((event.getX() <= getWidth() && event.getX() >= 0)
              && (event.getY() <= getHeight() && event.getY() >= 0)) {
            mState = 1;
            mStartTime = System.currentTimeMillis();
            invalidate();
          }

          break;
        case MotionEvent.ACTION_UP:

          changeBackgroundColor(getResources().getColor(android.R.color.transparent));
          press = false;
          if ((event.getX() <= getWidth() && event.getX() >= 0)
              && (event.getY() <= getHeight() && event.getY() >= 0)) {
            isLastTouch = false;
            check = !check;
            if (onCheckListener != null) onCheckListener.onCheck(RadioButton.this, check);
            if (check) checkView.changeBackground();
            mState = 3;
            mStartTime = System.currentTimeMillis();
          }

          invalidate();
          break;
        case MotionEvent.ACTION_CANCEL:
          mState = 1;
          invalidate();
          break;
      }
    }
    return true;
  }

  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (press) {
      Paint paint = new Paint();
      paint.setAntiAlias(true);
      paint.setColor((check) ? makePressColor() : getResources().getColor(R.color.md_ripple_color));
      canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
      invalidate();
    }
  }

  private void changeBackgroundColor(int color) {
    LayerDrawable layer = (LayerDrawable) getBackground();
    GradientDrawable shape = (GradientDrawable) layer.findDrawableByLayerId(R.id.shape_background);
    shape.setColor(color);
  }

  /**
   * Make a dark color to press effect
   * 
   * @return
   */
  protected int makePressColor() {
    int r = (this.backgroundColor >> 16) & 0xFF;
    int g = (this.backgroundColor >> 8) & 0xFF;
    int b = (this.backgroundColor >> 0) & 0xFF;
    r = (r - 30 < 0) ? 0 : r - 30;
    g = (g - 30 < 0) ? 0 : g - 30;
    b = (b - 30 < 0) ? 0 : b - 30;
    return Color.argb(70, r, g, b);
  }

  @Override
  public void setBackgroundColor(int color) {
    backgroundColor = color;
    if (isEnabled()) beforeBackground = backgroundColor;
    changeBackgroundColor(color);
  }

  public void setChecked(boolean check) {
    invalidate();
    this.check = check;
    setPressed(false);
    changeBackgroundColor(getResources().getColor(android.R.color.transparent));
    checkView.changeBackground();

  }

  public boolean isCheck() {
    return check;
  }

  class Check extends View {

    public Check(Context context) {
      super(context);
      setBackgroundResource(R.drawable.background_radio_uncheck);
    }

    public void changeBackground() {
      if (check) {
        setBackgroundResource(R.drawable.background_radio_check);
      } else {
        setBackgroundResource(R.drawable.background_radio_uncheck);
      }
    }

    @Override
    protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      long elapsed = System.currentTimeMillis() - mStartTime;
      int thumbRadius = check ? mThumbRadius : 0;
      if (mState == 3) {
        if (!check) {//更改圆环颜色
          changeBackground();
        }
        if (elapsed < 200) {
          if (check) {
            thumbRadius = Math.round(elapsed * mThumbRadius / 200);
          } else {
            thumbRadius = Math.round((200 - elapsed) * mThumbRadius / 200);
          }
        } else {
          mState = 1;
        }
        
        invalidate();
      }
      canvas.drawCircle(getWidth() / 2, getHeight() / 2, thumbRadius, thumbPaint);
    }

  }



  public void setOncheckListener(OnCheckListener onCheckListener) {
    this.onCheckListener = onCheckListener;
  }

  public interface OnCheckListener {
    public void onCheck(RadioButton view, boolean check);
  }

}
